import React, { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { getUserInfo } from '~/utils/crypto'
import { getBlogListXhr } from '~/api/index'
import { DEFAULT_AVATAR } from '~/const/index'
import { BLOG_TYPE_MAP } from '~/const/index'
import dayjs from 'dayjs'
import { useParams } from 'react-router-dom'

const PAGE_SIZE = 10

const CategoryPage: React.FC = () => {
  const { category } = useParams()
  const navigate = useNavigate()
  const userInfo = getUserInfo() || {}
  const [articles, setArticles] = useState<any[]>([])
  const [page, setPage] = useState(1)
  const [total, setTotal] = useState(0)
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    setLoading(true)
    getBlogListXhr({ page, pageSize: PAGE_SIZE, category: category }).then(
      (res: any) => {
        setArticles(res?.data?.list || [])
        setTotal(res?.data?.total || 0)
        setLoading(false)
      }
    )
  }, [page, category])

  const totalPages = Math.ceil(total / PAGE_SIZE)

  const getCategoryInfo = (category: string) => {
    switch (category) {
      case 'tech':
        return {
          title: '技术',
          icon: 'ri-code-line',
          color: 'text-blue-400',
        }
      case 'life':
        return {
          title: '生活',
          icon: 'ri-heart-line',
          color: 'text-green-400',
        }
      case 'thoughts':
        return {
          title: '思考',
          icon: 'ri-think-line',
          color: 'text-purple-400',
        }
      default:
        return {
          title: '未知分类',
          icon: 'ri-question-line',
          color: 'text-gray-400',
        }
    }
  }

  const categoryInfo = getCategoryInfo(category || '')

  return (
    <div className="container px-6 py-8">
      <div className="flex items-center gap-3 mb-8">
        <i
          className={`${categoryInfo.icon} ${categoryInfo.color} text-2xl`}
        ></i>
        <h3 className="text-2xl font-bold">{categoryInfo.title}</h3>
      </div>
      <div>
        <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-3 xl:grid-cols-4 gap-8">
          {loading ? (
            <div className="col-span-5 text-center text-gray-500">
              加载中...
            </div>
          ) : articles.length === 0 ? (
            <div className="col-span-5 text-center text-gray-400">暂无文章</div>
          ) : (
            articles.map((item) => (
              <div
                key={item.id}
                className="glass-card p-6 hover-scale"
                style={{ minHeight: 130 }}
                onClick={() => navigate(`/article/${item.id}`)}
              >
                <div className="flex items-center justify-between mb-4">
                  <span className="text-blue-400">
                    #
                    {item?.category
                      ? BLOG_TYPE_MAP?.[item?.category] || '技术'
                      : '技术'}
                  </span>
                  <span className="text-xs text-gray-400 ml-2">
                    <i className="ri-eye-line mr-1"></i> 阅读 {item.views || 0}
                  </span>
                </div>
                <h2 className="text-2xl font-bold mb-4 truncate">
                  {item.title}
                </h2>
                {item.content && item.content.replace(/<[^>]+>/g, '').trim() ? (
                  <p className="text-gray-500 dark:text-gray-300 mb-4 line-clamp-2">
                    {item.content.replace(/<[^>]+>/g, '').slice(0, 120)}...
                  </p>
                ) : (
                  <div className="h-[18px] mb-4"></div>
                )}
                <div className="flex items-center justify-between text-sm text-gray-400">
                  <div className="flex items-center">
                    <i className="ri-time-line mr-2"></i>
                    <span>
                      {item?.createdAt
                        ? dayjs(item.createdAt).format('YYYY-MM-DD')
                        : ''}
                    </span>
                  </div>
                  <div className="flex items-center ml-4">
                    <img
                      src={item?.authorAvatar || DEFAULT_AVATAR}
                      alt="avatar"
                      className="w-6 h-6 rounded-full mr-2"
                    />
                    <span className="text-gray-600">
                      {item?.authorName || '不知名网友'}
                    </span>
                  </div>
                </div>
              </div>
            ))
          )}
        </div>

        {articles.length > 0 && (
          <div className="flex justify-center mt-10">
            <nav className="inline-flex rounded-md shadow-sm">
              <button
                className="px-3 py-1 border border-gray-300 rounded-l-md bg-white hover:bg-gray-100 disabled:opacity-50"
                onClick={() => setPage(page - 1)}
                disabled={page === 1}
              >
                上一页
              </button>

              <div className="px-4 py-1 border-t border-b border-gray-300 bg-white text-gray-600">
                <span className="text-blue-600">{page}</span>/{totalPages}
              </div>
              <button
                className="px-3 py-1 border border-gray-300 rounded-r-md bg-white hover:bg-gray-100 disabled:opacity-50"
                onClick={() => setPage(page + 1)}
                disabled={page === totalPages}
              >
                下一页
              </button>
            </nav>
          </div>
        )}

        {!!userInfo?.roleLevel && (
          <button
            className="fixed bottom-12 right-20 bg-blue-500 text-white p-2 rounded-full shadow-lg flex items-center justify-center"
            onClick={() => navigate('/publish')}
          >
            <span className="text-xl mr-2">+</span> 发布博客
          </button>
        )}
      </div>
    </div>
  )
}

export default CategoryPage
